﻿using System;
using System.Collections.Generic;
using System.Linq; 

namespace CoolCode.Linq
{
    public interface IFilterable<T>
    {
        IQueryBuilder<T> CreateFilter();
    }

    public static class IFilterableExtensions
    {
        public static IFilterable<T> Join<T>(this IFilterable<T> current, IFilterable<T> other)
        {
            FilterLink<T> link;
            if (current is FilterLink<T>)
            {
                link = ((FilterLink<T>)current);
            }
            else
            {
                link = new FilterLink<T>(current.CreateFilter());
            }

            link.Add(other);
            return link;
        }
    }

    class FilterLink<T> : IFilterable<T>//, IQueryBuilder<T>
    {
        //private  Expression<Func<T, bool>>  Expression;

        private List<IQueryBuilder<T>> list;

        public FilterLink()
        {
            list = new List<IQueryBuilder<T>>();
        }

        public FilterLink(IQueryBuilder<T> queryBuilder)
            : this()
        {
            list.Add(queryBuilder);
        }

        //public FilterLink(Expression<Func<T, bool>> expression)
        //{
        //    this.Expression = expression;
        //}

        public void Add(IFilterable<T> other)
        {
            list.Add(other.CreateFilter());
        }


        public void Add(IQueryBuilder<T> other)
        {
            list.Add(other);
        }


        #region IFilterable<T> Members

        public IQueryBuilder<T> CreateFilter()
        {
            var result = new QueryBuilder<T>();
            foreach (var qb in list)
            {
                result.Custom(qb.Expression);
            }
            return result;
        }

        #endregion

        //#region IQueryBuilder<T> Members

        // Expression<Func<T, bool>> IQueryBuilder<T>.Expression
        //{
        //    get { return Expression; }
        //    set { Expression = value; }
        //}

        //#endregion
    }
}
